package com.opencore.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class ConexionSQL {

	private static Connection con = null;
	private static String url = null;
	private static String usuario = null;
	private static String password = null;

	public static Connection crearConeccionSQL() throws ClassNotFoundException{
		url = armaUrlConexion();
		usuario = (AppProperties.getProperty("aplicacion", "USUARIO"));
		password = (AppProperties.getProperty("aplicacion", "PASSWORD"));

		try{
			Class.forName("com.inet.tds.TdsDriver");
			con = DriverManager.getConnection(url, usuario, password);
		}
		catch(Exception e){
			System.out.println("Error contectando con la base de datos " + url);
		}
		return con;
	}

	public static void cierraConeccion() throws ClassNotFoundException{
		try {
			if(con != null)
				con.close();
		} catch (SQLException e) {
			System.out.println("Error al cerrar la conexion");
		}
	}

	private static String armaUrlConexion(){
		StringBuilder armarUrl = new StringBuilder();
		armarUrl.append("jdbc:inetdae7:").append(AppProperties.getProperty("aplicacion", "SERVIDOR"));
		armarUrl.append(":").append(AppProperties.getProperty("aplicacion", "PUERTO"));	
		armarUrl.append("?database=").append(AppProperties.getProperty("aplicacion", "BASEDATOS"));
		return armarUrl.toString();
	}

	public static int getLastRow(String key, String tabla) throws ClassNotFoundException{
		int correlativo = 0;
		con =  crearConeccionSQL();
		String query = "select max("+ key +") from " + tabla;
		Statement stmt = null;
		try {
			stmt = con.createStatement();
			ResultSet rs = stmt.executeQuery(query);
			while (rs.next()){
				correlativo = rs.getInt(1)+1;
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			cierraConeccion();
		}		
		return correlativo;
	}

	//	public static void main(String[] args) throws Exception {
	//		try {
	//			//crearConeccionSQL();			
	//			System.out.println(getLastRow("ID_DTE_LECTURA", "DTE_LECTURA"));
	//			
	//		} catch (ClassNotFoundException e) {
	//			System.out.println("Error de coneccion;");
	//		}finally{
	//			cierraConeccion();
	//		}
	//	}
}
